package exts

import (
	"context"
	"errors"
	"gitee.com/tietang/terrace-go/v2/base/plugin"
	"gitee.com/tietang/terrace-go/v2/example/order"
	"time"
)

var jdExt order.CreateOrderDomainExt = new(JdOrderCreatedDomainExt)
var _ plugin.PluginId = new(JdOrderCreatedDomainExt)
var _ plugin.RuleChecker = new(JdOrderCreatedDomainExt)

func init() {
	plugin.Register(jdExt)
}

type JdOrderCreatedDomainExt struct {
	order.CreateOrderDomainExt
}

func (o *JdOrderCreatedDomainExt) OnValidate(ctx context.Context, in *order.Order) error {
	if !in.TradeAmount.Equal(in.PayAmount) {
		return errors.New("交易金额和支付金额不一致")
	}
	return nil
}

func (o *JdOrderCreatedDomainExt) PreSave(ctx context.Context, in *order.Order) error {
	// JD 已支付状态
	in.Status = 1
	if in.BizDate == nil {
		//JD 凌晨2点之前算前一天营业日
		date := time.Now()
		date.Add(-time.Hour * 2)
		in.BizDate = &date
	}

	return nil
}

func (o *JdOrderCreatedDomainExt) Check(ctx context.Context, in interface{}) bool {
	dto := in.(*order.Order)
	return dto.Source == 1
}

func (o *JdOrderCreatedDomainExt) PluginCode() string {
	return order.CreateOrderDomainPluginId
}

func (o *JdOrderCreatedDomainExt) Ability() string {
	return "JD"
}
